﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace C_sports_meet
{
    /// <summary>
    /// ResetPwd.xaml 的交互逻辑
    /// </summary>
    public partial class ResetPwd : Window
    {
        public ResetPwd()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(ResetPwd_Loaded);
        }

        public static string CreateRandomCode(int length)//生成由数字和大小写字母组成的验证码
        {
            string list = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
            Random random = new Random();
            string code = "";//验证码
            for (int i = 0; i < length; i++)//循环得到一个伪随机的length位验证码
            {
                code += list[random.Next(0, list.Length - 1)];
            }
            return code;
        }


        private string code;
        private int cnt1, cnt2;
        private void re_Send_Click(object sender, RoutedEventArgs e)//发送按钮点击事件
        {
            string userid = re_UserName.Text.Trim();//账号
            string email = re_Email.Text.Trim();//邮箱
            if (!String.IsNullOrEmpty(userid) && !String.IsNullOrEmpty(email))//账号和邮箱不为空
            {
                SqlConnection connection = new SqlConnection("server=;database=sportmeet;user=sa;pwd=Lss200217");
                string sql3 = "select UserName , Email from dbo.Users where UserName ='" + userid + "' and Email='" + email + "'";
                SqlCommand command = new SqlCommand(sql3, connection);
                connection.Open();
                SqlDataReader data = command.ExecuteReader();
                if (data.HasRows)//若电子邮箱是注册时填写的邮箱
                {
                    try
                    {
                        MailMessage mail = new MailMessage();  //实例化一个发送邮件类
                        mail.From = new MailAddress("1541175606@qq.com");   //发件人邮箱地址
                        mail.To.Add(new MailAddress(email));    //收件人邮箱地址
                        mail.Subject = "【运动会管理系统V1.0】找回密码";    //邮件标题
                        code = CreateRandomCode(6);   //生成伪随机的6位数验证码
                        mail.Body = "验证码是: " + code + "，请在5分钟内进行验证。验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗。系统邮件请勿回复。";  //邮件内容          
                        SmtpClient client = new SmtpClient("smtp.qq.com");   //实例化一个SmtpClient类。
                        client.EnableSsl = true;    //使用安全加密连接
                        client.Credentials = new NetworkCredential("1541175606@qq.com", "rybfbgodsfkyfeja");//验证发件人身份(发件人的邮箱，邮箱里的生成授权码);        
                        client.Send(mail);
                        //计时器初始化
                        cnt1 = 60;
                        cnt2 = 1200;
                        timer1.IsEnabled = true;//timer1用来记录一分钟
                        timer2.IsEnabled = true;//timer2用来记录两分钟
                        re_Send.IsEnabled = false;//发送按钮不可点击
                        MessageBox.Show("发送成功！");
                       
                    }
                    catch (Exception msg)
                    {
                        MessageBox.Show(msg.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("该邮箱不是账号绑定的邮箱。", "失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("请将账号和邮箱填写完整！", "警告", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        //创建对象
        private DispatcherTimer timer1, timer2;
        void ResetPwd_Loaded(object sender, RoutedEventArgs e)
        {
            //实例化对象
            timer1 = new DispatcherTimer();
            timer2 = new DispatcherTimer();
            //设置触发时间
            timer1.Interval = TimeSpan.FromSeconds(1);
            timer2.Interval = TimeSpan.FromSeconds(1);
            //设置触发事件
            timer1.Tick += Timer1_Tick;
            timer2.Tick += Timer2_Tick;
            //启动
            timer1.Start();
            timer2.Start();
        }



        private void Timer1_Tick(object sender, EventArgs e)//发送完邮件，需要60秒后才能再次发送
        {

            if (cnt1 > 0)
            {
                cnt1--;
                re_Send.Content = "发送(" + cnt1 + ")";
            }
            else
            {
                timer1.IsEnabled = false;
                re_Send.IsEnabled = true;
                re_Send.Content = "发送";

            }
        }

        private void backButtonClick(object sender, RoutedEventArgs e)
        {
            Login login = new Login();
            this.Close();
            login.Show();
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            if (cnt2 == 0)
            {
                timer2.IsEnabled = false;
                code = CreateRandomCode(6);//旧的验证码过期，生成一个新的
            }
        }

        private void re_Button_Click(object sender, RoutedEventArgs e)
        {
            string rpassword = re_RtxtPwd.Text.Trim();
            string username = re_UserName.Text.Trim();
            if (string.Compare(re_Code.Text.Trim(), code, true) == 0)
            {
                try
                {
                    SqlConnection sqlConnection = new SqlConnection(@"Server=DESKTOP-EM7AB45;Database=sportmeet;Integrated Security=True");
                    string sql = "Update [dbo].[Users] set PassWord = '" + rpassword + "'Where UserName='" + username + "'";
                    SqlCommand command = new SqlCommand(sql, sqlConnection);

                    SqlParameter sqlParameter = new SqlParameter("@UserName", username);
                    command.Parameters.Add(sqlParameter);
                    sqlParameter = new SqlParameter("@PassWord", rpassword);
                    command.Parameters.Add(sqlParameter);

                    sqlConnection.Open();
                    command.ExecuteNonQuery();//执行sql并返回执行的行数
                    sqlConnection.Close();
                    MessageBox.Show("更改密码成功！");
                    Login login = new Login();
                    this.Close();
                    login.Show();
                }
                catch (SqlException) //返回警告
                {
                    MessageBox.Show("数据库连接错误！");
                }
            }
            else
            {
                MessageBox.Show("验证码错误！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
